//
//  WHYSQLiteManeger.swift
//  FMDB
//
//  Created by 王洪运 on 15/12/8.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

private let dbName = "readme.db"

class WHYSQLiteManeger {
    
    static let sharedManager = WHYSQLiteManeger()
    
    let queue: FMDatabaseQueue
    
    private init() {
        
//        数据库全路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent(dbName)
        QL2(path)
        
//        打开数据库队列 -- 如果数据库不存在，则会自动创建
        queue = FMDatabaseQueue(path: path)
     
        createTable()
    }
    
    func execRecordSet(sql: String) -> [[String: AnyObject]] {
        
        var result = [[String: AnyObject]]()
        
        queue.inDatabase { (db) -> Void in
            
            guard let rs = db.executeQuery(sql) else {
                QL4("没有结果")
                return
            }
            
            while rs.next() {
                
                let colCount = rs.columnCount()
                
                var dict = [String: AnyObject]()
                
                for col in 0..<colCount {
                    
                    let name = rs.columnNameForIndex(col)
                    let obj = rs.objectForColumnIndex(col)
                    
                    dict[name] = obj
                    
                }
                
                result.append(dict)
                
            }
            
        }
        
       return result
    }
    
    private func createTable () {
        
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        let sql = try! String(contentsOfFile: path)
        
        queue.inDatabase { (db) -> Void in
            
            if db.executeStatements(sql) {
                QL2("创表成功")
            }else {
                QL4("创表失败")
            }
            
        }
        
    }

}
